package com.proxy.socks5;

import io.netty.channel.*;
import io.netty.handler.codec.http.*;

/**
 * @author kdyzm
 * @date 2021/4/26
 */
public class BlackListInboundHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (!(msg instanceof HttpRequest)) {
            System.out.println("非http请求，直接关闭channel");
            ctx.channel().close();
            return;
        }
        HttpRequest request = (HttpRequest) msg;
        System.out.println("请求方式：" + request.method().name());
        System.out.println("请求uri：" + request.uri());
        if ("/favicon.ico".equalsIgnoreCase(request.uri())) {
            System.out.println("不处理 /favicon.ico 请求");
            return;
        }
        HttpResponse response = new DefaultHttpResponse(request.protocolVersion(), HttpResponseStatus.OK);
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");
        boolean keepAlive = HttpUtil.isKeepAlive(request);
        if (keepAlive) {
            response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        }
        ctx.write(response);
        ChannelFuture future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
        if (!keepAlive) {
            future.addListener(ChannelFutureListener.CLOSE);
        }
        ctx.flush();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        ctx.channel().close();
    }
}
